package com.liaoyifan.core.aspect;

import com.liaoyifan.core.annotation.DS;
import com.liaoyifan.core.datasource.DataSourceHolder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;

@SuppressWarnings("unused")
@Aspect
@Order(-1)
public class DataSourceAspect {

    private static final Logger log = LogManager.getLogger(DataSourceAspect.class.getSimpleName());

    @Around(
            "@annotation(com.liaoyifan.core.annotation.DS) || @within(com.liaoyifan.core.annotation.DS)")
    public Object proceed(ProceedingJoinPoint joinPoint) throws Throwable {
        DS ds = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(DS.class);
        if (ds == null) {
            ds = AnnotationUtils.findAnnotation(joinPoint.getTarget().getClass(), DS.class);
        }
        if (ds == null) {
            return joinPoint.proceed();
        }
        try {
            String value = ds.value();
            DataSourceHolder.set(value);
            log.info("DataSourceHolder set: {}", value);
            return joinPoint.proceed();
        } finally {
            DataSourceHolder.clear();
            log.info("DataSourceHolder clear");
        }
    }
}
